package com.kz.controller;

import com.alibaba.fastjson.JSONObject;
import com.kz.ShiroCasConfiguration;
import com.kz.entity.sys.SysUser;
import com.kz.service.sys.SysUserService;
import com.kz.userservice.SysUserRpcService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import tools.common.enums.ResultEnum;
import tools.util.DateUtil;
import tools.util.UUIDGenerator;
import tools.util.ValidateUtil;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author kz
 * @date 2017年12月1日14:32:07
 * @desc 项目首页
 */
@Controller
@RequestMapping(value = "/")
public class GlobalController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final Integer USERNAME_MINI_LENGTH = 2;

    private static final Integer PASSWORD_MINI_LENGTH = 6;

    @RequestMapping("/login")
    public String login() {
        return "front/login";
    }


    @RequestMapping("/register")
    public String register() {
        return "front/register";
    }


    @Autowired
    private SysUserRpcService sysUserRpcService;

    /**
     * 注册
     *
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject register(HttpServletRequest request) {
        JSONObject result = new JSONObject();
        String email = request.getParameter("email");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        result.put("code", ResultEnum.STATUS.FAIL.getCode());
        if (StringUtils.isBlank(email)) {
            result.put("msg", "邮箱不能为空");
            return result;
        }
        if (!ValidateUtil.verifyEmailIsPassed(email)) {
            result.put("msg", "邮箱不正确");
            return result;
        }
        if (sysUserRpcService.querySysUserByEmail(email) > 0) {
            result.put("msg", "该邮箱已经存在");
            return result;
        }
        if (StringUtils.isBlank(username)) {
            result.put("msg", "账号昵称不能为空");
            return result;
        }
        if (username.length() < USERNAME_MINI_LENGTH) {
            result.put("msg", "账户名称太短");
            return result;
        }
        if (StringUtils.isBlank(password)) {
            result.put("msg", "密码不能为空");
            return result;
        }
        if (password.length() < PASSWORD_MINI_LENGTH) {
            result.put("msg", "密码太短");
            return result;
        }

        SysUser user = new SysUser();
        user.setId(UUIDGenerator.getUUID());
        user.setEmail(email);
        user.setUsername(username);
        user.setPassword(password);
        user.setInsertDate(new Date());
        user.setLastUpdate(new Date());
        sysUserRpcService.save(user);
        result.put("code", ResultEnum.STATUS.SUCCESS.getCode());
        result.put("msg", "注册成功");
        logger.info("用户:{},邮箱:{},注册成功,时间:{}", username, email, DateUtil.format(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS));
        return result;

    }

    /**
     * ajax登录请求
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String submitLogin(String username,String password,
                                           Boolean rememberMe, HttpServletRequest request) {

        UsernamePasswordToken token = new UsernamePasswordToken(username, password, false);
        SecurityUtils.getSubject().login(token);
        SavedRequest savedRequest = WebUtils.getSavedRequest(request);
        // 获取保存的URL
        if (savedRequest == null || savedRequest.getRequestUrl() == null) {
            return "redirect:" + ShiroCasConfiguration.shiroServerUrlPrefix;
        }
        return "redirect:" + ShiroCasConfiguration.loginUrl;
    }

    /**
     * 退出
     *
     * @return
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> logout() {
        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
        try {
            //退出
            SecurityUtils.getSubject().logout();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return resultMap;
    }
}
